/*
 * (C) 2005 National Australia Bank
 *
 * [All rights reserved]. This product and related documentation are protected
 * by copyright restricting its use, copying, distribution, and decompilation.
 * No part of this product or related documentation may be reproduced in any
 * form by any means without prior written authorization of
 * National Australia Bank. Unless otherwise arranged, third parties may not
 * have access to this product or related documents.
 */

package parser;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.lang.StringUtils;
/**
 * Seeds customers for several functional tests.<br/>
 * <br/>
 * @version $Id: @(#) CreateCustomersDataSeeder.java@@\main\2  2009-02-18 23:21:28 GMT  p656354d $
 */
public class SCStats {

    private static final String TOO_SERIOUS_URL = "http://tooserious.net";
    
	public void execute() {
    	String[] teams = new String[] {"ADE", "BRL", "CAR", "COL", "ESS", "FRE", "GEE", "HAW", "KAN", "MEL", "PTA", "RIC", "STK", "SYD", "WBD", "WCE"};
    	BufferedWriter output = null;
    	HttpClient client = new HttpClient();
		
        try {
        	output = new BufferedWriter(new FileWriter("c:\\output.csv"));
        	output.write("Surname,Firstname,Position,Team,Price,Total Points,Games,Last Round,Breakeven,Average,Next Round,3 Rounds\n");
        	
        	for (int k = 0; k < teams.length; k++) {
        		System.out.println("processing: " + teams[k]);
        		for (int j = 1; j <= 3; j++) {
        			String response = getResponse(client, teams[k], j);
		            processResponse(output, response, teams[k]);
        		}
        	}
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {
        	try {
        		output.close();
        	}
        	catch (Exception e) {
                e.printStackTrace();
            }	
        }
    }

	private void processResponse(BufferedWriter output, String response, String team)
			throws Exception, IOException {
		List<String> results = Arrays.asList(response.split("\n"));
		
		for (Iterator<String> listIter = results.iterator(); listIter.hasNext();) {
			String line = listIter.next();
			if (line.indexOf("<strong>") != -1) {
				String result = "";
				result += line.substring(line.indexOf("<strong>") + 8, line.indexOf(",")).trim().toUpperCase() + ",";
				result += line.substring(line.indexOf("</strong>") + 9, line.indexOf("</font>")).trim() + ",";
				
				line = getLine(listIter);
				result += line.substring(line.indexOf("value=") + 7, line.indexOf("value=") + 10) + ",";
				
				result += team + ",";
				
				getLine(listIter);//</td>
				
				for (int count = 1; count <= 8; count++) {
					result += getItem(listIter).replace(",", "");
					if (count < 8)  result += ",";
				}
				output.write(result + "\n");
			}
		}
	}

	private String getResponse(HttpClient client, String team, int j)
			throws IOException, HttpException {
		
		HttpMethod method = new GetMethod(TOO_SERIOUS_URL);
		String queryString = "page=main";
		if (j == 1) queryString += "&steam=" + team;
		queryString += "&page_num=" + j;
		method.setQueryString(queryString);
		client.executeMethod(method);
		String response = StringUtils.trimToEmpty(method.getResponseBodyAsString());
		
		return response;
	}
	
	public void testGetResponse() {
		try {
			HttpClient client = new HttpClient();
			System.out.println(getResponse(client, "ADE", 1));
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void testProcessResponse() {
		try {
			BufferedWriter output = new BufferedWriter(new FileWriter("c:\\output.csv")); 
			HttpClient client = new HttpClient();
			String response = getResponse(client, "ADE", 1);
	        processResponse(output, response, "ADE");
	        response = getResponse(client, null, 2);
	        processResponse(output, response, "ADE");
	        response = getResponse(client, null, 3);
	        processResponse(output, response, "ADE");
	        
	        
	        output.close();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private String getLine(Iterator<String> listIter) throws Exception {
		String line = listIter.next();
		while (line.length() == 0 && listIter.hasNext()) {
			line = listIter.next();
		}
		
		return line;
	}

	private String getItem(Iterator<String> listIter) throws Exception {
		String line;
		line = getLine(listIter);
		String salary = line.substring(line.indexOf(">") + 1, line.indexOf("</"));
		return salary;
	}
    
	public static void main(String[] args) {
		SCStats seeder = new SCStats();
		seeder.execute();
		
		//seeder.testProcessResponse();
	}
}
